#ifndef PLCGRAPHICSSCENE_H
#define PLCGRAPHICSSCENE_H

#include <QGraphicsScene>
#include "plcelement.h"
#include "connectionitem.h"

class QGraphicsView;
class QGraphicsSceneMouseEvent;

class PlcGraphicsScene : public QGraphicsScene
{
    Q_OBJECT
public:
    enum Mode { Normal, CreateItem };

    explicit PlcGraphicsScene(QGraphicsView* view, QObject* parent = nullptr);

    void setMode(Mode mode);
    void setInstructionTypeToCreate(PlcInstructionType type);
    void deleteSelectedItems();

    // 重建每行最左侧的锚点圆
    void rebuildRowAnchors();

    // 安全清空场景（同时清空锚点指针数组）
    void clearAll();

    // 连线拖动方法
    void startConnectionDrag(PlcElement* element, bool fromRight);
    void updateConnectionDrag(const QPointF& scenePos);
    void endConnectionDrag(const QPointF& scenePos);

    // 网格吸附（以网格中心为准）
    QPointF cellCenterAt(const QPointF& scenePos) const;
    QPointF snapTopLeftToCellCenter(const QPointF& scenePos, const QSizeF& item) const;

    void setGridOriginX(double x);
    double gridOriginX() const;

    // 复制/粘贴
    void copyFrom(const PlcElement* src);
    bool canPaste() const;
    PlcElement* pasteAt(const QPointF& scenePos);

    // 尝试将 element 插入其当前位置下方/附近命中的“水平 ConnectionItem”中
    bool insertConnection(PlcElement* element);

signals:
    void elementCreated(PlcElement* item);
    // 当场景内容被改动（删除/粘贴/插入等）时发出
    void sceneContentChanged();

protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
    void drawBackground(QPainter* painter, const QRectF& rect) override;
    void keyPressEvent(QKeyEvent *event) override;

    // 空白处右键“粘贴”
    void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override;

private:
    Mode m_mode;
    PlcInstructionType m_typeToCreate;
    QGraphicsView* m_view;

    // 连线拖动状态
    PlcElement* m_dragElement = nullptr;
    bool m_dragFromRight = false;
    QGraphicsLineItem* m_tempLine = nullptr;

    // 网格属性
    QSizeF m_gridSize = QSizeF(83, 53); // 网格大小 (略大于元件尺寸)
    bool m_showGrid = true; // 是否显示网格
    double  m_gridOriginX = 35.0; // 网格原点：绘制与吸附统一用这个偏移

    // 每行x=0的锚点小圆
    QVector<QGraphicsEllipseItem*> m_rowAnchors;
    static constexpr int kAnchorRadius = 3;

    // 剪贴板
    struct CopiedElement {
        bool valid = false;
        PlcInstructionType type = PlcInstructionType::NormallyOpen;
        QSizeF size = QSizeF(60.0, 35.0);
        bool on = false;
        // 属性对话框里的值
        QString prefix = QStringLiteral("M");
        int v1 = 0;   // 对应 m_propValue
        int v2 = 0;   // 对应 m_propValue2
    } m_clip;
};

#endif // PLCGRAPHICSSCENE_H
